package com.check.ui;

import com.check.bean.CheckRuleBean;
import com.check.bean.LoggerString;
import com.check.utils.Rule;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.util.Properties;

import static com.check.utils.PropertiesUtils.*;

/**
 * @description:
 * @Author: zyt
 */
public class CheckRuleStage extends Stage {
    private Rule rule = new Rule();

    public CheckRuleStage() {
        AnchorPane anchorPane = new AnchorPane();
        this.setScene(new Scene(anchorPane, 600, 400));
        TableView<CheckRuleBean> tableView = new TableView<>();
        tableView.setEditable(true);
        TableColumn<CheckRuleBean, String> column1 = new TableColumn<>("名称");
        TableColumn<CheckRuleBean, String> column2 = new TableColumn<>("检查规则");
        column1.setPrefWidth(150);
        column1.setCellValueFactory(data -> data.getValue().ruleNameProperty());
        column1.setCellFactory(TextFieldTableCell.forTableColumn());
        column1.setOnEditCommit(event -> {
            final CheckRuleBean editBean = event.getRowValue();
            final String newValue = event.getNewValue();
            final String oldValue = event.getOldValue();
            if (newValue.isEmpty()) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("输入错误!");
                alert.setContentText("你输入的名称为空!请重新输入!");
                alert.showAndWait();
                return;
            }
            if (newValue.equals(oldValue)) {
                return;
            }
            Properties pro = getPropertiesValue("/checkRule.properties");

            if (pro.get(newValue) != null) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("名称重复");
                alert.setContentText("检查的名称不能重复,请重新输入!");
                alert.showAndWait();
                tableView.refresh();
                return;
            } else {
                // 删除
                pro.remove(editBean.getRuleName(), editBean.getRuleValue());
                // 修改
                editBean.setRuleName(newValue);
                // 写入对象
                pro.put(editBean.getRuleName(), editBean.getRuleValue());
                // 刷新
                tableView.refresh();
            }
            // 写入硬盘
            setPropertiesValue(pro, "/checkRule.properties");
            System.out.println("success");
        });
        column1.setSortable(false);
        column2.setPrefWidth(150);
        column2.setCellValueFactory(date -> date.getValue().ruleValueProperty());
        column2.setCellFactory(TextFieldTableCell.forTableColumn());
        column2.setOnEditCommit(event -> {
            final CheckRuleBean editBean = event.getRowValue();
            final String newValue = event.getNewValue();
            Properties pro = getPropertiesValue("/checkRule.properties");
            pro.setProperty(editBean.getRuleName(),newValue);
            setPropertiesValue(pro, "/checkRule.properties");
            System.out.println("success");
        });
        column2.setSortable(false);
        tableView.getColumns().setAll(column1, column2);
        tableView.setItems(this.getData());
        tableView.setMaxWidth(300);

        Label nameLabel = new Label("名称");
        nameLabel.setLayoutX(310);
        nameLabel.setLayoutY(20);
        TextField nameText = new TextField();
        nameText.setLayoutX(350);
        nameText.setLayoutY(20);
        nameText.setPrefWidth(200);

        Label regLabel = new Label("规则");
        regLabel.setLayoutX(310);
        regLabel.setLayoutY(80);
        TextField valueText = new TextField();
        valueText.setLayoutX(350);
        valueText.setLayoutY(80);
        valueText.setPrefWidth(200);

        Label lengthLabel = new Label("长度");
        lengthLabel.setLayoutX(310);
        lengthLabel.setLayoutY(160);
        TextField lengthTextLeft = new TextField();
        lengthTextLeft.setLayoutX(350);
        lengthTextLeft.setLayoutY(160);
        lengthTextLeft.setPrefWidth(90);
        TextField lengthTextRight = new TextField();
        lengthTextRight.setLayoutX(460);
        lengthTextRight.setLayoutY(160);
        lengthTextRight.setPrefWidth(90);

        Label rangeLabel = new Label("范围");
        rangeLabel.setLayoutX(310);
        rangeLabel.setLayoutY(220);
        TextField rangeTextLeft = new TextField();
        rangeTextLeft.setLayoutX(350);
        rangeTextLeft.setLayoutY(220);
        rangeTextLeft.setPrefWidth(90);
        TextField rangeTextRight = new TextField();
        rangeTextRight.setLayoutX(460);
        rangeTextRight.setLayoutY(220);
        rangeTextRight.setPrefWidth(90);

        Button addButton = new Button("添加");
        addButton.setLayoutX(350);
        addButton.setLayoutY(280);
        Button delButton = new Button("删除");
        delButton.setLayoutX(500);
        delButton.setLayoutY(280);
        addButton.setOnAction(actionEvent -> {
            if (nameText.getText().length() <= 0) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("输入错误!");
                alert.setContentText("你输入的名称为空!请重新输入!");
                alert.showAndWait();
                return;
            }
            if (getPropertiesValue("/checkRule.properties").containsKey(nameText.getText())) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("输入错误!");
                alert.setContentText("你输入的名称已存在!请重新输入!");
                alert.showAndWait();
                return;
            }
            String reg = valueText.getText();
            // 判断规则输入框是否有数据,如果有就进行下一步,如果没有就从范围数据框中读取
            if (reg.length() == 0) {
                reg = lengthReg(lengthTextLeft, lengthTextRight);
            }
            // 判断两个长度输入框是否有数据,如果有就进行下一步,如果没有就从范围输入框中读取数据
            if (reg.length() == 0) {
                reg = rangeReg(rangeTextLeft, rangeTextRight);
            }
            // 读取三次之后如果没有数据的话,说明三个输入框都没有数据输入.此时反回
            if (reg.length() == 0) {
                return;
            }

            Properties pro = getPropertiesValue("/checkRule.properties");
            pro.setProperty(nameText.getText(), reg);
            tableView.getItems().add(new CheckRuleBean(nameText.getText(), reg));
            LoggerString.stringBuffer.append("添加规则:" + nameText.getText() + "\n");
            setPropertiesValue(pro, "/checkRule.properties");
            nameText.clear();
            valueText.clear();
            lengthTextLeft.clear();
            lengthTextRight.clear();
            rangeTextLeft.clear();
            rangeTextRight.clear();
        });
        delButton.setOnAction(e -> {
            final CheckRuleBean selectedItem = tableView.getSelectionModel().getSelectedItem();
            if (selectedItem == null) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("信息!");
                alert.setContentText("请先选中要删除的项!");
                alert.showAndWait();
                return;
            }
            final Properties propertiesValue = getPropertiesValue("/checkRule.properties");
            propertiesValue.remove(selectedItem.getRuleName());
            setPropertiesValue(propertiesValue, "/checkRule.properties");
            tableView.getItems().removeAll(selectedItem);
        });

        anchorPane.getChildren().setAll(tableView, addButton, delButton, nameText, valueText, nameLabel, regLabel
                , lengthLabel, rangeLabel, rangeTextLeft, rangeTextRight, lengthTextLeft, lengthTextRight);
    }

    public ObservableList<CheckRuleBean> getData() {
        Properties pro = getPropertiesValue("/checkRule.properties");
        final ObservableList<CheckRuleBean> list = FXCollections.observableArrayList();
        pro.forEach((k, v) -> {
            CheckRuleBean bean = new CheckRuleBean();
            bean.setRuleName((String) k);
            bean.setRuleValue((String) v);
            list.add(bean);
        });
        return list;
    }

    private String lengthReg(TextField lengthTextLeft, TextField lengthTextRight) {
        // 长度规则
        String reg = "^.{" + lengthTextLeft.getText() + "," + lengthTextRight.getText() + "}$";
        return getReg(lengthTextLeft, lengthTextRight, reg);
    }

    private String rangeReg(TextField rangeTextLeft, TextField rangeTextRight) {
        // 范围规则
        String reg = "!@@" + rangeTextLeft.getText() + ":" + rangeTextRight.getText();
        return getReg(rangeTextLeft, rangeTextRight, reg);
    }

    private String getReg(TextField textLeft, TextField textRight, String regVal) {
        String reg = "";

        if (!checkNumber(textLeft)) {
            return reg;
        }

        if (!checkNumber(textRight)) {
            return reg;
        }

        String rangeLeft = textLeft.getText();
        String rangeRight = textRight.getText();
        if (!compare(rangeLeft, rangeRight)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告!");
            alert.setContentText("右边的数字不能小于左边!");
            alert.showAndWait();
            textRight.requestFocus();
            return reg;
        }
        reg = regVal;
        return reg;
    }

    private boolean checkNumber(TextField textField) {
        String text = textField.getText();
        if (text.length() == 0) {
            return false;
        }
        if (!rule.isIntNum(text)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告!");
            alert.setContentText("输入框只能输入数字!");
            alert.showAndWait();
            textField.requestFocus();
            return false;
        }
        return true;
    }

    private boolean compare(String left, String right) {
        return Integer.parseInt(right) > Integer.parseInt(left);
    }

}
